/*
 * @Description: 路由解析中间件
 * @Author: YangHeng
 * @Date: 2021-08-09 16:53:52
 * @FilePath: \web_server\node_modules\civiapp\middleware\router.js
 */

const url = require("url");

module.exports = () => {
  return async (ctx, next) => {
    // console.log('路由中间件', ctx.req)
    // let aaa = url.parse(req.url);
    // let router_path = ctx.req.url.split('?')[0].split('/').filter(item => item)

    // 解析路由路径
    let utlPath = ctx.req.url.split('?')[0]
    if (utlPath[utlPath.length-1] == '/')
    utlPath = utlPath.substr(0, utlPath.length-1)

    // 匹配路由表中的路由
    let match = false
    civi.routerTable.some(router => {
      // 请求方式无限制 或者 复合限制条件
      if (!router[2] || router[2].toLocaleUpperCase().indexOf(ctx.method) !== -1) {
        if (typeof router[0] === 'object') {
          // 按正则匹配
          if (router[0].test(utlPath)) match = router
        } else {
          if (router[0].toLocaleLowerCase() === utlPath) match = router // 路由全匹配
          else { // path参数路由匹配
            let path1 = router[0].split('/').filter(item => item)
            let path2 = utlPath.split('/').filter(item => item)
            if (path1.length === path2.length) { // 路由路径长度要相等
              let params = {}, _match = true
              path1.forEach((item, index) => {
                let item1 = path2[index]
                if (item.indexOf(':') === -1) {
                  if (item.toLocaleLowerCase() !== item1.toLocaleLowerCase()) _match = false
                } else params[item.split(':')[1]] = item1
              })
              if (_match) {
                match = router
                Object.assign(ctx.request.query, params)
              }
            }
          }
        }
      }
      return !!match
    })

    // 分配控制器
    if (!!match) ctx.controller = match[1]
    else ctx.controller = utlPath.substr(1)
    
    await next()
  }
}